package com.jsmile.cloud.taskcenter.task;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

import org.quartz.SchedulerException;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.jsmile.cloud.taskcenter.api.req.*;
import com.jsmile.cloud.taskcenter.api.res.ResTask;
import com.jsmile.cloud.taskcenter.task.model.TaskModel;
import com.jsmile.cloud.taskcenter.task.repo.TaskRepository;

import cn.hutool.core.bean.BeanUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
@AllArgsConstructor
public class TaskApplicationService {

    private final TaskRepository taskRepository;

    public boolean saveTask(ReqTaskInsert reqTaskInsert) {
        try {
            return taskRepository.saveTask(BeanUtil.toBean(reqTaskInsert, TaskModel.class));
        } catch (SchedulerException e) {
            return false;
        }
    }

    public void pauseJob(ReqBatchTaskDetail reqTaskDetail) {
        Collection<TaskModel> tasks = taskRepository.listByIds(reqTaskDetail.getIds());
        tasks.forEach(task -> {
            try {
                taskRepository.pauseJob(task);
            } catch (SchedulerException e) {
                e.printStackTrace();
            }
        });
    }

    public void resumeJob(ReqBatchTaskDetail reqTaskDetail) {
        Collection<TaskModel> tasks = taskRepository.listByIds(reqTaskDetail.getIds());
        tasks.forEach(task -> {
            try {
                taskRepository.resumeJob(task);
            } catch (SchedulerException e) {
                e.printStackTrace();
            }
        });
    }

    public void runJob(ReqBatchTaskDetail reqTaskDetail) {
        Collection<TaskModel> tasks = taskRepository.listByIds(reqTaskDetail.getIds());
        tasks.forEach(task -> {
            taskRepository.runJob(task);
        });
    }

    public boolean deleteTasks(ReqTaskDelete reqTaskDelete) {
        return taskRepository.deleteTasks(reqTaskDelete);
    }

    public IPage<ResTask> page(ReqTaskQuery reqTaskQuery) {
        return taskRepository.page(reqTaskQuery).convert(taskModel -> BeanUtil.toBean(taskModel, ResTask.class));
    }

    public List<ResTask> list(ReqTaskQuery reqTaskQuery) {
        return taskRepository.list(reqTaskQuery).stream().map(taskModel -> BeanUtil.toBean(taskModel, ResTask.class)).collect(Collectors.toList());
    }

    public ResTask detail(ReqTaskDetail reqTaskDetail) {
        return BeanUtil.toBean(taskRepository.getById(reqTaskDetail.getId()), ResTask.class);
    }
}
